import tool.TreeNode;

import java.awt.event.MouseAdapter;

/**
 * @Description: 平衡二叉树
 * 给定一个二叉树，判断它是否是高度平衡的二叉树。
 * <p>
 * 本题中，一棵高度平衡二叉树定义为：
 * 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1
 * @Date:Create in 18:49  2022/7/26
 */
public class isBalanced0110 {
//    private boolean flag;
//    public boolean flag=true;

    public static boolean isBalanced(TreeNode root) {
        if (root == null) return true;
//        boolean flag;
        int left = treeDeep(root.left);
        int right = treeDeep(root.right);
        if (Math.abs(left - right) > 1) {
            return false;
        }
        return true;
    }

    public static int treeDeep(TreeNode root) {
        if (root == null) return 0;
        int left = treeDeep(root.left);
        int right = treeDeep(root.right);
        return Math.max(left, right) + 1;
    }

    //递归
    public static boolean isBalanced1(TreeNode root) {
        return getHeight(root) != -1;
    }

    public static int getHeight(TreeNode root) {
        if (root == null) return 0;
        int leftHeight = getHeight(root.left);
        if (leftHeight == -1) {
            return -1;
        }
        int rightHeight = getHeight(root.right);
        if (rightHeight == -1) {
            return -1;
        }

        if (Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        }
        return Math.max(leftHeight, rightHeight) + 1;
    }
}
